using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.interfaces;
using umbraco.presentation.cache;
using umbraco.uicontrols;
using umbraco.controls;
using Commerce.Common;
using Commerce.Promotions;

namespace CommerceForUmbraco.adminSection.commerce
{
    public partial class editProduct : umbraco.BasePages.UmbracoEnsuredPage
    {
        #region properties

        public TabPage MainTab;
        public TabPage CategoryTab;
        public TabPage ImageTab;
        public TabPage DescriptorTab;
        public TabPage AttributeTab;
        public TabPage CrossSellTab;

        //Media Pickers
        private umbraco.editorControls.mediaChooser _mediaPicker;
        private MediaPickerDataExtractor _mediaPickerExtractor;

        // Product
        Product thisProduct;

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            string productId = Request.QueryString.Get("p");
            thisProduct = new Product(int.Parse(productId));

            if (!IsPostBack)
            {
                ProductName.Text = thisProduct.ProductName;
                ProductSku.Text = thisProduct.Sku;
                ShortDescription.Text = thisProduct.ShortDescription;
                OurPrice.Text = thisProduct.OurPrice.ToString();
                RetailPrice.Text = thisProduct.RetailPrice.ToString();

                // manufacturer
                ManufacturerCollection manufacturers = new ManufacturerCollection().OrderByAsc("Manufacturer").Load();
                Manufacturer.Items.Clear();
                foreach (Manufacturer thisMan in manufacturers)
                {
                    Manufacturer.Items.Add(new ListItem(thisMan.ManufacturerX, thisMan.ManufacturerID.ToString()));
                }
                Manufacturer.SelectedIndex = Manufacturer.Items.IndexOf(Manufacturer.Items.FindByValue(thisProduct.ManufacturerID.ToString()));

                // status
                ProductStatussCollection productStatus = new ProductStatussCollection().Load();
                Status.Items.Clear();
                foreach (ProductStatuss thisStatus in productStatus)
                {
                    Status.Items.Add(new ListItem(thisStatus.Status, thisStatus.StatusID.ToString()));
                }
                Status.SelectedIndex = Status.Items.IndexOf(Status.Items.FindByValue(thisProduct.StatusID.ToString()));

                // product type
                ProductTypesCollection productTypes = new ProductTypesCollection().Load();
                ProductType.Items.Clear();
                foreach (ProductTypes thisType in productTypes)
                {
                    ProductType.Items.Add(new ListItem(thisType.ProductType, thisType.ProductTypeID.ToString()));
                }
                ProductType.SelectedIndex = ProductType.Items.IndexOf(ProductType.Items.FindByValue(thisProduct.ProductTypeID.ToString()));

                // shipping type
                ShippingTypesCollection shippingTypes = new ShippingTypesCollection().Load();
                ShippingType.Items.Clear();
                foreach (ShippingTypes thisShipType in shippingTypes)
                {
                    ShippingType.Items.Add(new ListItem(thisShipType.ShippingType, thisShipType.ShippingTypeID.ToString()));
                }
                ShippingType.SelectedIndex = ShippingType.Items.IndexOf(ShippingType.Items.FindByValue(thisProduct.ShippingTypeID.ToString()));

                // shipping estimate
                ShippingEstimatesCollection shipEstimates = new ShippingEstimatesCollection().Load();
                ShipEstimate.Items.Clear();
                foreach (ShippingEstimates thisShipEstimate in shipEstimates)
                {
                    ShipEstimate.Items.Add(new ListItem(thisShipEstimate.ShippingEstimate, thisShipEstimate.ShipEstimateID.ToString()));
                }
                ShipEstimate.SelectedIndex = ShipEstimate.Items.IndexOf(ShipEstimate.Items.FindByValue(thisProduct.ShipEstimateID.ToString()));

                // tax type
                TaxTypeCollection taxTypes = new TaxTypeCollection().Load();
                TaxTypeDDL.Items.Clear();
                foreach (TaxType thisTaxType in taxTypes)
                {
                    TaxTypeDDL.Items.Add(new ListItem(thisTaxType.TaxTypeX, thisTaxType.TaxTypeID.ToString()));
                }
                TaxTypeDDL.SelectedIndex = TaxTypeDDL.Items.IndexOf(TaxTypeDDL.Items.FindByValue(thisProduct.TaxTypeID.ToString()));

                // currency code
                UtilCurrencyCollection currencyCodes = new UtilCurrencyCollection().Load();
                CurrencyCodeDDL.Items.Clear();
                foreach (UtilCurrency thisCurrency in currencyCodes)
                {
                    CurrencyCodeDDL.Items.Add(new ListItem(thisCurrency.Code, thisCurrency.CodeID.ToString()));
                }
                CurrencyCodeDDL.SelectedIndex = CurrencyCodeDDL.Items.IndexOf(CurrencyCodeDDL.Items.FindByValue(thisProduct.CurrencyCode));

                // weight
                Weight.Text = thisProduct.Weight.ToString();

                // dimensions - w, l h
                // TODO:  add dimensions

                //admin comments
                AdminComments.Text = thisProduct.AdminComments;

                // category
                CategoryCollection categories = new CategoryCollection().OrderByAsc("categoryName").Load();
                categoryDDL.Items.Clear();
                foreach (Category thisCat in categories)
                {
                    categoryDDL.Items.Add(new ListItem(thisCat.CategoryName, thisCat.CategoryID.ToString()));
                }
                if (thisProduct.GetCategoryCollection().Count > 0)
                    categoryDDL.SelectedIndex = categoryDDL.Items.IndexOf(categoryDDL.Items.FindByValue(thisProduct.GetCategoryCollection()[0].CategoryID.ToString()));

                categoryList.DataSource = CategoryController.GetByProductID(thisProduct.ProductID);
                categoryList.DataBind();

                // image media
                _mediaPicker.Value = thisProduct.DefaultImage;

                // descriptors
                rptDescriptors.DataSource = ProductController.GetDescriptors(thisProduct.ProductID);
                rptDescriptors.DataBind();

                // attributes
                // TODO: v1.1

                // cross-sell
                ProductCollection prods = ProductController.GetAll();
                ListItem item;
                chkProducts.Items.Clear();
                foreach (Product prod in prods)
                {
                    item = new ListItem(prod.ProductName, prod.ProductID.ToString());
                    chkProducts.Items.Add(item);
                }
                // load the cross-sell products for this product
                ProductCollection crosses = PromotionService.GetCrossSells(thisProduct.ProductID).OrderByAsc("ProductName");
                foreach (Product cross in crosses)
                {
                    foreach (ListItem l in chkProducts.Items)
                    {
                        if (int.Parse(l.Value) == cross.ProductID)
                            l.Selected = true;
                    }
                }

            }
             
            // Main Tab Labels
                this.Pane1.Text = "Edit Product";
                this.pp_name.Text = "Product Name";
                this.pp_sku.Text = "SKU";
                this.pp_short_description.Text = "Short Description";
                this.pp_our_price.Text = "Our Price";
                this.pp_retail_price.Text = "Retail Price";
                this.pp_manufacturer.Text = "Manufacturer";
                this.pp_status.Text = "Status";
                this.pp_product_type.Text = "ProductType";
                this.pp_shipping_type.Text = "Shipping Type";
                this.pp_ship_estimate.Text = "Ship Estimate";
                this.pp_tax_type.Text = "Tax Type";
                this.pp_stock_location.Text = "Stock Location";
                this.pp_weight.Text = "Weight";
                this.pp_currency_code.Text = "Currency Code";
                this.pp_admin_comments.Text = "Admin Comments";

                // Category Tab Labels
                this.Pane2.Text = "Product Categories";
                this.pp_categories.Text = "Category";
                this.pp_category_list.Text = "Assigned Categories";

                // Image Tab Labels
                this.Pane3.Text = "Product Image";
                this.pp_images.Text = "Image";

                // DescriptorTab Labels
                this.Pane4.Text = "Product Descriptors";
                this.pp_add_descriptor_list_order.Text = "List Order";
                this.pp_add_descriptor_title.Text = "Title";
                this.pp_add_descriptor_text.Text = "Text or List";
                this.pp_descriptor_list.Text = "Descriptors";

                // AttributeTab Labels
                //this.Pane5.Text = "Product Attributes";

                // CrossSellTab Labels
                this.Pane6.Text = "Product Cross Sell Items";
        }

        private bool SaveProduct(string productName, string productId)
        {
            Product product = new Product("ProductID",int.Parse(productId));

            Product.BeforeSaveProduct(product);

            decimal _OurPrice = 0;
            decimal _RetailPrice = 0;
            decimal _Weight = 0;

            try
            {
                product.ProductName = this.ProductName.Text;
                product.Sku = this.ProductSku.Text;
                product.ShortDescription = this.ShortDescription.Text;
                if (decimal.TryParse(this.OurPrice.Text, out _OurPrice))
                    product.OurPrice = _OurPrice;
                else
                    product.OurPrice = 0;
                if (decimal.TryParse(this.RetailPrice.Text, out _RetailPrice))
                    product.RetailPrice = _RetailPrice;
                else
                    product.RetailPrice = 0;
                product.ManufacturerID = int.Parse(this.Manufacturer.SelectedItem.Value);
                product.StatusID = int.Parse(this.Status.SelectedItem.Value);
                product.ProductTypeID = int.Parse(this.ProductType.SelectedItem.Value);
                product.ShippingTypeID = int.Parse(this.ShippingType.SelectedItem.Value);
                product.ShipEstimateID = int.Parse(this.ShipEstimate.SelectedItem.Value);
                product.TaxTypeID = int.Parse(this.TaxTypeDDL.SelectedItem.Value);
                product.CurrencyCode = this.CurrencyCodeDDL.SelectedItem.Value;
                if (decimal.TryParse(this.Weight.Text, out _Weight))
                    product.Weight = _Weight;
                else
                    product.Weight = 0;
                product.AdminComments = this.AdminComments.Text;

                // image
                if (_mediaPicker.Value != "")
                {
                    umbraco.cms.businesslogic.media.Media m = new umbraco.cms.businesslogic.media.Media(int.Parse(_mediaPicker.Value));
                 
                    product.DefaultImage = m.Id.ToString();
                    // also create a record in CSK_Store_Image - dashCommerce legacy requirement
                    Commerce.Common.Image img = new Commerce.Common.Image(true);
                    img.ImageFile = m.Id.ToString();
                    img.Caption = product.ProductName;
                    img.ProductID = product.ProductID;
                    ImageCollection productImages = new ImageCollection().Load();
                    productImages.Clear();
                    productImages.Add(img);
                    productImages.SaveAll("Commerce for Umbraco");
                }
                
                product.Save("Commerce for Umbraco");
                
                // cross sell
                Utility.SaveManyToMany("productID", product.ProductID, "CSK_Promo_Product_CrossSell_Map", "crossProductID", chkProducts.Items);
                
                Product.AfterSaveProduct(product);

                return true;
            }
            catch
            {
                return false;
            }
        }

        #region button handlers
        
        private void save_click(object sender, ImageClickEventArgs e)
        {
            if (this.SaveProduct(this.ProductName.Text, base.Request.QueryString["p"]))
            {
                base.speechBubble(0, ui.Text("speechBubbles", "commerceItemSaved"), "");
            }
            else
            {
                base.speechBubble(0, ui.Text("speechBubbles", "commerceItemErrorHeader"), ui.Text("speechBubbles", "commerceItemErrorText"));
            }
        }

        protected void categoryAddButton_Click(object sender, EventArgs e)
        {
            ProductController.AddToCategory(thisProduct.ProductID, int.Parse(categoryDDL.SelectedItem.Value.ToString()));
            categoryList.DataSource = CategoryController.GetByProductID(thisProduct.ProductID);
            categoryList.DataBind();
        }

        protected void categoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string sCatID = e.CommandArgument.ToString();
            ProductController.RemoveFromCategory(thisProduct.ProductID, int.Parse(sCatID));
            categoryList.DataSource = CategoryController.GetByProductID(thisProduct.ProductID);
            categoryList.DataBind();
        }

        protected void SaveDescriptorButton_Click(object sender, EventArgs e)
        {
            ProductDescriptor pd = new ProductDescriptor();
            try
            {
                pd.ListOrder = int.Parse(DescriptorListOrder.Text);
            }
            catch
            {
            }
            pd.Title = DescriptorTitle.Text;
            pd.Descriptor = DescriptorText.Text;
            pd.IsBulletedList = chkIsBulletedList.Checked;
            pd.ProductID = thisProduct.ProductID;
            pd.Save("Commerce for Umbraco");

            rptDescriptors.DataSource = ProductController.GetDescriptors(thisProduct.ProductID);
            rptDescriptors.DataBind();
        }

        protected void rptDescriptors_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int descriptorID = 0;

            if (e.CommandArgument != null)
            {
                descriptorID = int.Parse(e.CommandArgument.ToString());
                if (e.CommandName == "delete")
                {
                    ProductDescriptor.Delete(descriptorID);
                }

                rptDescriptors.DataSource = ProductController.GetDescriptors(thisProduct.ProductID);
                rptDescriptors.DataBind();
            }
        }

        #endregion

        #region load routines
        protected override void OnInit(EventArgs e)
        {

            // Tab setup
            MainTab = tabControl.NewTabPage("Main");
            MainTab.Controls.Add(Pane1);

            CategoryTab = tabControl.NewTabPage("Categories");
            CategoryTab.Controls.Add(Pane2);

            ImageTab = tabControl.NewTabPage("Images");
            ImageTab.Controls.Add(Pane3);

            DescriptorTab = tabControl.NewTabPage("Descriptors");
            DescriptorTab.Controls.Add(Pane4);

            //AttributeTab = tabControl.NewTabPage("Attributes");
            //AttributeTab.Controls.Add(Pane5);

            CrossSellTab = tabControl.NewTabPage("Cross Sell");
            CrossSellTab.Controls.Add(Pane6);

            // Main Tab
            ImageButton save = MainTab.Menu.NewImageButton();
            save.Click += new ImageClickEventHandler(this.save_click);
            save.AlternateText = "Save";
            save.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // Category Tab
            ImageButton save2 = CategoryTab.Menu.NewImageButton();
            save2.Click += new ImageClickEventHandler(this.save_click);
            save2.AlternateText = "Save";
            save2.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // Images Tab
            ImageButton save3 = ImageTab.Menu.NewImageButton();
            save3.Click += new ImageClickEventHandler(this.save_click);
            save3.AlternateText = "Save";
            save3.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // DescriptorTab
            ImageButton save4 = DescriptorTab.Menu.NewImageButton();
            save4.Click += new ImageClickEventHandler(this.save_click);
            save4.AlternateText = "Save";
            save4.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // AttributeTab
            //ImageButton save5 = AttributeTab.Menu.NewImageButton();
            //save5.Click += new ImageClickEventHandler(this.save_click);
            //save5.AlternateText = "Save";
            //save5.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // CrossSellTab
            ImageButton save6 = CrossSellTab.Menu.NewImageButton();
            save6.Click += new ImageClickEventHandler(this.save_click);
            save6.AlternateText = "Save";
            save6.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            //Media Pickers
            _mediaPickerExtractor = new MediaPickerDataExtractor();
            _mediaPicker = new umbraco.editorControls.mediaChooser(_mediaPickerExtractor);
            _mediaPicker.ID = "mediapicker";
            pnlMediaPicker.Controls.Add(_mediaPicker);


            base.Load += new EventHandler(this.Page_Load);
            this.InitializeComponent();
            base.OnInit(e);


        }

        private void InitializeComponent()
        {
        }
        #endregion

  
    }
}
